package com.wyl.template.config;

import com.wyl.template.config.shiro.CustomRealm;
import com.wyl.template.config.shiro.CustomSessionIdGenerator;
import com.wyl.template.config.shiro.CustomSessionManager;
import com.wyl.template.config.shiro.MyLogoutFilter;
import com.wyl.template.config.shiro.filter.CustomRolesOrAuthorizationFilter;
import com.wyl.template.config.shiro.filter.MyFormAuthenticationFilter;
import com.wyl.template.config.shiro.filter.MyUserFilter;
import com.wyl.template.constant.AppConstants;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Auther: wyl
 * @Date: 2021/4/29
 * @Description:
 */
@Configuration
public class ShiroConfig implements EnvironmentAware {

    /**
     * redis配置信息
     * Configuration 无法注入配置文件信息，通过实现EnvironmentAware，重写setEnvironment方法可以获得配置信息
     */
    private String host;
    private int port;
    private int database;
    private int timeout;
    private String password;
    private final static String redisSeparator = ":";

    // 过期时间，1800秒
    private final static int DEFAULT_EXPIRE = 1800;
    // 1秒=1000毫秒
    static final long MILLIS_PER_SECOND = 1000;


    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //必须设置securityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        //需要登录的接口，如果访问某个接口，需要登录却没登录，则调用此接口(如果不是前后端分离，则跳转页面)
        shiroFilterFactoryBean.setLoginUrl("/pub/need_login");
        //登录成功，跳转url，如果前后端分离，则没这个调用
        shiroFilterFactoryBean.setSuccessUrl("/");
        //没有权限，未授权就会调用此方法， 先验证登录-》再验证是否有权限
        shiroFilterFactoryBean.setUnauthorizedUrl("/pub/v1/not_permit");

        //设置自定义filter
        Map<String, Filter> filterMap = new LinkedHashMap<>();
        filterMap.put("roleOrFilter", new CustomRolesOrAuthorizationFilter());
        filterMap.put("logout", new MyLogoutFilter());
        filterMap.put("authc", new MyFormAuthenticationFilter());
        filterMap.put("user", new MyUserFilter());
        shiroFilterFactoryBean.setFilters(filterMap);

        //拦截器路径，坑一，部分路径无法进行拦截，时有时无；因为同学使用的是hashmap, 无序的，应该改为LinkedHashMap
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        //退出过滤器
        filterChainDefinitionMap.put("/logout", "logout");
        //匿名可以访问，也是就游客模式
        filterChainDefinitionMap.put("/pub/**", "anon");
//        filterChainDefinitionMap.put("/api/user/**", "anon");
//        filterChainDefinitionMap.put("/api/role/**", "anon");
        //登录用户才可以访问
        filterChainDefinitionMap.put("/authc/**", "authc");
        //管理员角色才可以访问
        filterChainDefinitionMap.put("/admin/**", "roleOrFilter[admin,root]");
        //有编辑权限才可以访问
//        filterChainDefinitionMap.put("/video/update", "perms[video_update]");
        //坑二: 过滤链是顺序执行，从上而下，一般讲/** 放到最下面

        //authc : url定义必须通过认证才可以访问
        //anon  : url可以匿名访问
        //user : 需要认证或通过记住我认证才能访问
        filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        //如果不是前后端分离，则不必设置下面的sessionManager
        securityManager.setSessionManager(sessionManager());

        //使用自定义的cacheManager
        securityManager.setCacheManager(cacheManager());

        //设置realm（推荐放到最后，不然某些情况会不生效）
        securityManager.setRealm(customRealm());

        return securityManager;
    }


    /**
     * 自定义realm
     *
     * @return
     */
    @Bean
    public CustomRealm customRealm() {
        CustomRealm customRealm = new CustomRealm();

        customRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return customRealm;
    }


    /**
     * 密码加解密规则
     *
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();

        //设置散列算法：这里使用的MD5算法
        credentialsMatcher.setHashAlgorithmName(AppConstants.DEFAULT_HASH_NAME);

        //散列次数，好比散列2次，相当于md5(md5(xxxx))
        credentialsMatcher.setHashIterations(AppConstants.DEFAULT_HASH_TIMES);

        return credentialsMatcher;
    }


    //自定义sessionManager
    @Bean
    public SessionManager sessionManager() {

        CustomSessionManager customSessionManager = new CustomSessionManager();

        //超时时间，默认 30分钟，会话超时；方法里面的单位是毫秒
        customSessionManager.setGlobalSessionTimeout(DEFAULT_EXPIRE * MILLIS_PER_SECOND);

        //配置session持久化
        customSessionManager.setSessionDAO(redisSessionDAO());

        // 某些 chrome 版本下同一个服务器部署多个 java 应用会出现 JSESSIONID 冲突的问题
        Cookie cookie = new SimpleCookie(AppConstants.DEFAULT_SESSION_ID_NAME);
        customSessionManager.setSessionIdCookie(cookie);
        return customSessionManager;
    }


    /**
     * 配置redisManager
     */
    public RedisManager getRedisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host + redisSeparator + port);
        redisManager.setDatabase(database);
        redisManager.setPassword(password);
        redisManager.setTimeout(timeout);
//        redisManager.setJedisPool();
        return redisManager;
    }


    /**
     * 配置具体cache实现类
     *
     * @return
     */
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(getRedisManager());

        //设置过期时间，单位是秒，默认 30分钟
        redisCacheManager.setExpire(DEFAULT_EXPIRE);

        return redisCacheManager;
    }


    /**
     * 自定义session持久化
     *
     * @return
     */
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(getRedisManager());

        //设置sessionid生成器
        redisSessionDAO.setSessionIdGenerator(new CustomSessionIdGenerator());

        return redisSessionDAO;
    }


    /**
     * 管理shiro一些bean的生命周期 即bean初始化 与销毁
     *
     * @return
     */
    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }


    /**
     * api controller 层面
     * 加入注解的使用，不加入这个AOP注解不生效(shiro的注解 例如 @RequiresGuest)
     *
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
        return authorizationAttributeSourceAdvisor;
    }


    /**
     * 用来扫描上下文寻找所有的Advistor(通知器),
     * 将符合条件的Advisor应用到切入点的Bean中，需要在LifecycleBeanPostProcessor创建后才可以创建
     *
     * @return
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setUsePrefix(true);
        return defaultAdvisorAutoProxyCreator;
    }


    /**
     * 设置环境信息，获得配置信息
     *
     * @param environment
     */
    @Override
    public void setEnvironment(Environment environment) {
        this.host = environment.getProperty("spring.redis.host");
        this.port = Integer.valueOf(environment.getProperty("spring.redis.port"));
        this.database = Integer.valueOf(environment.getProperty("spring.redis.database"));
        this.password = environment.getProperty("spring.redis.password");
        this.timeout = Integer.valueOf(environment.getProperty("spring.redis.timeout"));
    }
}
